package com.cskaoyan.user.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cskaoyan.mall.commons.result.ResponseData;
import com.cskaoyan.mall.commons.result.ResponseUtil;
import com.cskaoyan.mall.commons.util.CookieUtil;
import com.cskaoyan.user.constants.UserRetCode;
import com.cskaoyan.user.dto.UserInfo;
import com.cskaoyan.user.dto.UserLoginPostRequest;
import com.cskaoyan.user.dto.UserLoginResponse;
import com.cskaoyan.user.form.UserLoginPost;
import com.cskaoyan.user.service.UserLoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/user")
public class UserLoginController {

    private static final int MAX_AGE = 3600;

    @Autowired
    UserLoginService userLoginService;

    @PostMapping("/login")
    public ResponseData loginPost(@RequestBody UserLoginPost loginPost, HttpServletResponse resp, HttpServletRequest req){

        UserLoginPostRequest request = new UserLoginPostRequest();
        String uuid = CookieUtil.getCookieValue(req, "kaptcha_uuid");
        request.setUuid(uuid);
        request.setUserName(loginPost.getUserName());
        request.setUserPwd(loginPost.getUserPwd());
        request.setCaptcha(loginPost.getCaptcha());
        UserLoginResponse response = userLoginService.userLoginPost(request);
        if (UserRetCode.SUCCESS.getCode().equals(response.getCode())) {
            // 执行成功，直接返回前端需要的数据
            Cookie cookie = CookieUtil.genCookie("access_token", response.getToken(), "/", MAX_AGE);
            resp.addCookie(cookie);
            return new ResponseUtil().setData(response);
        }
        // 调用失败
        return  new ResponseUtil().setErrorMsg(response.getMsg());
    }

    @GetMapping("/login")
    public ResponseData loginGet(HttpServletRequest servletRequest ){
        String userInfo = (String) servletRequest.getHeader("user_info");
        JSONObject object = JSON.parseObject(userInfo);
        Long uid = Long.parseLong(object.get("uid").toString());
        String username = (String) object.get("username");


        return new ResponseUtil().setData( new UserInfo(username, uid));


    }
}

